package com.mrobuy.auth;

import com.mrobuy.jdvc.dao.JDAccountDao;
import com.mrobuy.jdvc.entity.JDAccount;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.net.URLEncoder;

@Controller
public class SNSAuthController {

	public static String APPKEY = "FEAFBABCDEEC48A569A10818138D7841";
	public static String APPSECRET = "36c196b5b2ea4c2aaaae6d80010a28a8";

	@Autowired
	private JDAccountDao jdAccountDao;


	@RequestMapping("/")
	public String index() {
		return "productapply";
	}

	@RequestMapping("/authorization")
	public String authorization() {

		String url = "https://open-oauth.jd.com/oauth2/to_login?app_key=" + APPKEY + "&response_type=code&redirect_uri=" + URLEncoder.encode("http://tgavel.vaiwan.com/sns_auth") + "&state=20180416&scope=snsapi_base";

		return "redirect:" + url;
	}

	@RequestMapping("/sns_auth")
	@ResponseBody
	public Object sns_auth(HttpServletRequest request) {

		try {
			String code = ServletRequestUtils.getStringParameter(request, "code");
			String state = ServletRequestUtils.getStringParameter(request, "state");


			RestTemplate restTemplate = new RestTemplate();


			JDAccount account = restTemplate.getForObject("https://open-oauth.jd.com/oauth2/access_token?app_key={1}&app_secret={2}&grant_type=authorization_code&code={2}", JDAccount.class,APPKEY, APPSECRET, code);



			JDAccount exist = jdAccountDao.load(APPKEY);
			if ( exist==null ) {

				account.setAppkey(APPKEY);
				account.setAppsecret(APPSECRET);

				jdAccountDao.insert(account);
			} else {

				exist.setAccess_token(account.getAccess_token());
				exist.setExpires_in(account.getExpires_in());
				exist.setRefresh_token(account.getRefresh_token());
				exist.setTime(account.getTime());
				exist.setUid(account.getUid());
				exist.setOpen_id(account.getOpen_id());
				exist.setCode(account.getCode());
				exist.setToken_type(account.getToken_type());
				exist.setScope(account.getScope());

				jdAccountDao.updatess(exist);
			}




			return  account;




		} catch (ServletRequestBindingException e) {
			e.printStackTrace();
		}

		return "Greetings from Spring Boot!";
	}

}
